<?php

namespace Cck\ArticlesSystem\Http\Controllers;

use Cck\ArticlesSystem\Http\Models\User;
use Cck\ArticlesSystem\Http\Resources\UserResource;
use Cck\ArticlesSystem\Http\Requests\UserLoginRequest;
use Cck\ArticlesSystem\Http\Resources\KeywordResource;

class AuthController extends Controller
{
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(UserLoginRequest $request)
    {
        $credentials = $request->validated();

        if (!$token = auth('api')->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        /** @var User $user */
        $user = auth('api')->user();
        $user->load($this->getWith());

        return (new UserResource($user))->additional($token->toResponse($request)->getData(true));
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        $user = auth()->user();

        $user->load($this->getWith());

        return new UserResource($user);
    }

    public function keywords()
    {
        return KeywordResource::collection(
            auth()->user()->keywords
        );
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        /** @var User $user */
        $user = auth('api')->user();
        $user->load($this->getWith());

        return (new UserResource($user))->additional(auth()->refresh()->toResponse(request())->getData(true));
    }
}
